<?php
// 2020年2月17日22:05:38
namespace app\index\controller\wanlshop;
use addons\wanlshop\library\WanlChat\WanlChat;
use addons\ymyauexpress\library\Express;
use addons\ymyauexpress\library\Expressty;
use app\common\controller\Wanlshop;
use addons\wanlshop\library\Ehund;
use app\common\library\QueueApi;
use think\Cache;
use think\Exception;

//快递100订阅

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Wanlshop
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    /**
     * Order模型对象
     */
    protected $model = null;
    protected $wanlchat = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\index\model\wanlshop\Order;
        $kuaidi = new \app\index\model\wanlshop\Kuaidi;
		$this->wanlchat = new WanlChat();
        $this->view->assign("kuaidiList", $kuaidi->field('name,code')->select());
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("statesList", $this->model->getStatesList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user','pay','ordergoods'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user','pay','ordergoods'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['id','username','nickname','avatar']);
                $row->getRelation('pay')->visible(['pay_no','price','order_price','freight_price','discount_price','actual_payment']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    
    
    /**
     * 详情
     */
    public function detail($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 判断权限
        if ($row['shop_id'] != $this->shop->id) {
            $this->error(__('You have no permission'));
        }
        $row['address'] = model('app\index\model\wanlshop\OrderAddress')
            ->where(['order_id' => $id, 'shop_id' => $this->shop->id])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name,number')
            ->find();
        $row['freight'] = model('app\api\model\wanlshop\ShopFreight')->where('id', $row['freight_id'])->find();
		// 查询快递状态
		switch ($row['state']) {
			case 1:
				$express = [
					'context' => '付款后，即可将宝贝发出',
					'status' => '尚未付款',
					'time' => date('Y-m-d H:i:s', $row['createtime'])
				];
				break;
			case 2:
				$express = [
					'context' => '商家正在处理订单',
					'status' => '已付款',
					'time' => date('Y-m-d H:i:s', $row['paymenttime'])
				];
				break;
			default: // 获取物流
				$eData = model('app\api\model\wanlshop\KuaidiSub')
					->where(['express_no' => $row['express_no']])
					->find();
				// 获取数据
				$ybData = json_decode($eData['data'], true);
				if($ybData){
					// 运单状态 1.0.6升级
					$statusText = ['在途','揽收','疑难','签收','退签','派件','退回','转投'];
					$status = $statusText[0];
					if(in_array('status', $ybData[0])){
						$status = $ybData[0]['status'];
					}else{
						if($eData['ischeck'] === 1){
							$status = $statusText[3];
						}else{
							$status = $statusText[$eData['state']];
						}
					}
					$express = [
						'status' => $status,
						'context' => $ybData[0]['context'],
						'time' => $ybData[0]['time'],
					];
				}else{
					$express = [
						'status' => '已发货',
						'context' => '包裹正在等待快递小哥揽收~',
						'time' => date('Y-m-d H:i:s', $row['delivertime'])
					];
				}
		}
		$this->view->assign("kuaidi", $express);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
	
	/**
	 * 快递查询
	 */
	public function relative($id = null)
	{
		$row = $this->model->get($id);
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		// 判断权限
		if ($row['shop_id'] != $this->shop->id) {
		    $this->error(__('You have no permission'));
		}
        if($row['delivery_mode'] == 'instead'){
            $config = get_addon_config('ymyauexpress');
        }else{
            $config = model('app\index\model\wanlshop\ShopConfig')
                ->field('au_member_id,au_password')
                ->where('shop_id',$row['shop_id'])
                ->find();
        }
        if(!$config){
            $this->error('请在店铺管理-店铺配置-澳邮配置参数');
        }
        $data = Cache::get($row['express_no'].'_track');
        if(!$data){
            if($row['express_no'][0]=="G"){
                $express = new Expressty();
                $data = $express->track($row['express_no']);
                $data = array_reverse($data);
                Cache::set($row['express_no'].'_track',$data,600);
            }else{
                $express = new Express($config['au_member_id'],$config['au_password']);
                $data = $express->track(['OrderId'=>$row['express_no']]);
                $data = array_reverse($data);
                Cache::set($row['express_no'].'_track',$data,600);
            }
        }
		$list = [];
		$week = array("0"=>"星期日","1"=>"星期一","2"=>"星期二","3"=>"星期三","4"=>"星期四","5"=>"星期五","6"=>"星期六");
		if($data){
			foreach($data as $vo){
				$list[] = [
					'time' => strtotime($vo['StatusTime']),
					'status' => '在途'/*$vo['id_OrderStatus']*/, // 1.0.6升级
					'context' => $vo['StatusDetail'],
					'week' => $week[date('w', strtotime($vo['StatusTime']))]
				];
			}
		}else{
            $list = [
                'status' => '已发货',
                'context' => '包裹等待揽收~',
                'time' => date('Y-m-d H:i:s', $row['delivertime'])
            ];
        }
		$this->view->assign("week", $week);
		$this->view->assign("list", $list);
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
    
    /**
     * 打印发货单
     */
    public function invoice($ids = null)
    {
        $row = $this->model->all($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $print_urls = [];
        foreach ($row as $data) {
            if($data['print_url']) {
                $print_urls[] = $data['print_url'];
            }
        }
        $this->view->assign("print_urls", $print_urls);
        return $this->view->fetch();
    }
    
    /**
     * 澳邮 发货 & 批量发货
     */
    public function delivery($ids = null)
    {
        $config = model('app\index\model\wanlshop\ShopConfig')
            ->field('au_member_id,au_password')
            ->where('shop_id',$this->shop->id)
            ->find();
        if(!$config){
            $this->error('请在店铺管理-店铺配置-澳邮配置参数');
        }

        $express = new Express($config['au_member_id'],$config['au_password']);
        $brands = Cache::get($config['au_member_id'].'brands') ?? [];


        if(empty($brands)){
            $brands = $express->brand();
            Cache::set($config['au_member_id'].'brands',$brands,86400);
        }


        $data = [];
        $lists = [];
        $row = $this->model->all($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        foreach ($row as $vo) {
            if ($vo['shop_id'] != $this->shop->id) {
                $this->error(__('You have no permission'));
            }
            $vo['address'] = model('app\index\model\wanlshop\OrderAddress')
                ->where(['order_id' => $vo['id'], 'shop_id' => $this->shop->id])
                ->order('isaddress desc')
                ->field('id,name,mobile,address,address_name,number')
                ->find();
            if ($vo['state'] == 2 && $vo['freight_type'] !== 99) {
                $lists[] = $vo;
            } else {
                $data[] = $vo;
            }
        }
        if ($this->request->isAjax()) {
            $request = $this->request->post();
            if (!array_key_exists("order", $request['row'])) {
                $this->success(__('没有发现可以发货订单~'));
            }
			if(!$this->wanlchat->isWsStart()){
				$this->error('平台未启动IM即时通讯服务，暂时不可以发货');
			}
            $orderAll = [];
			foreach ($request['row']['order']['id'] as $key => $id) {
			    try{
                    $order = model('app\api\model\wanlshop\Order')->get($id,['goods']);
                    $address = model('app\index\model\wanlshop\OrderAddress')
                        ->where(['order_id' => $id, 'shop_id' => $this->shop->id])
                        ->order('isaddress desc')
                        ->field('id,name,mobile,address,address_name,number,image_front,image_back')
                        ->find();

                    $addressDetail = explode('/',$address['address']);
                    $ShipmentContent = '';
                    foreach ($order['goods'] as $goods){
                        $ShipmentContent .= $goods['title'].'*'.$goods['number'].';';
                    }
                    $shopConfig = model('app\api\model\wanlshop\ShopConfig')->where('shop_id',$this->shop->id)->find();
                    $params = [
                        "BrandID"=> $request['row']['BrandId'],
                        "SenderName"=> $shopConfig['sendName'],
                        "SenderPhone"=> $shopConfig['sendPhoneNum'],
                        "ReceiverName"=> $address['name'],
                        "ReceiverPhone"=> $address['mobile'],
                        "ReceiverProvince"=> $addressDetail[0],
                        "ReceiverCity"=> $addressDetail[1],
                        "ReceiverAddr1"=> $addressDetail[2].$addressDetail[3].$address['address_name'],
                        "ShipmentContent"=> $ShipmentContent,
                        "Notes"=> $order['remarks'],
                    ];
                    $express = new Express($shopConfig['au_member_id'],$shopConfig['au_password']);
                    $express_no = $express->create($params);
                    $orderAll[] = [
                        'id' => $id,
                        'express_name' => '澳优国际速递',
                        'express_no' => $express_no,
                        'delivertime' => time(),
                        'delivery_mode' => 'self',
                        'state' => 3
                    ];
                    QueueApi::auUploadIdcard([
                        'id' => $id,
                        'shop_id' => $this->shop->id,
                        'express_no' => $express_no,
                    ],5);
                    QueueApi::auPrint([
                        'id' => $id,
                        'shop_id' => $this->shop->id,
                    ],5);
                    // 推送消息
                    $this->pushOrder($id,'已发货');
                }catch (Exception $e){
			        $this->error($e->getMessage());
                }

            }
            $this->model->saveAll($orderAll);
            $this->success();
        }
        $this->view->assign("lists", $lists); // 可以发货
        $this->view->assign("data", $data); // 不可以发货

        foreach ($brands as $k=>$b){
            if($b['initial']!='A'){
                unset($brands[$k]);
            }
        }
        $this->view->assign("brands", $brands); // 品牌列表
        return $this->view->fetch();
    }

    /**
     * 代发 &批量代发
    */
    public function instead($ids = null){

        $data = [];
        $lists = [];
        $row = $this->model->all($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        foreach ($row as $vo) {
            if ($vo['shop_id'] != $this->shop->id) {
                $this->error(__('You have no permission'));
            }
            $vo['address'] = model('app\index\model\wanlshop\OrderAddress')
                ->where(['order_id' => $vo['id'], 'shop_id' => $this->shop->id])
                ->order('isaddress desc')
                ->field('id,name,mobile,address,address_name,number')
                ->find();
            if ($vo['state'] == 2 && $vo['freight_type'] !== 99 && $vo['delivery_mode'] == 'created') {
                $lists[] = $vo;
            } else {
                $data[] = $vo;
            }
        }
        if ($this->request->isAjax()) {
            $request = $this->request->post();
            if(!isset($request['row'])){
                $this->error(__('没有发现可以发货订单~'));
            }
            if (!array_key_exists("order", $request['row'])) {
                $this->error(__('没有发现可以发货订单~'));
            }
            if(!$this->wanlchat->isWsStart()){
                $this->error('平台未启动IM即时通讯服务，暂时不可以发货');
            }
            $orderAll = [];
            foreach ($request['row']['order']['id'] as $key => $id) {
                try{

                    $orderAll[] = [
                        'id' => $id,
                        'delivery_mode' => 'instead',
                    ];

                }catch (Exception $e){
                    $this->error($e->getMessage());
                }

            }
            $this->model->saveAll($orderAll);
            $this->success();
        }
        $this->view->assign("lists", $lists); // 可以发货
        $this->view->assign("data", $data); // 不可以发货
        return $this->view->fetch();
    }

    // 上传客户身份证
    public function uploadIdcard(){
        if($this->request->isPost()){
            $order_id = $this->request->post('order_id');
            $order_id ? $order_id : ($this->error(__('非法请求')));
            $order = model('app\api\model\wanlshop\Order')->get($order_id,['goods']);
            QueueApi::auUploadIdcard([
                'id' => $order_id,
                'shop_id' => $this->shop->id,
                'express_no' => $order['express_no'],
            ],5);
            $this->success(__('上传成功,数据异步传输,请等待10秒左右刷新查看状态'));
        }
    }
    
    /**
     * 评论管理
     */
    public function comment()
    {
        return $this->view->fetch('wanlshop/comment/index');
    }
	
	/**
	 * 订单推送消息（方法内使用）
	 * 
	 * @param string order_id 订单ID
	 * @param string state 状态
	 */
	private function pushOrder($order_id = 0, $state = '已发货')
	{
		$order = $this->model->get($order_id);
		$orderGoods = model('app\index\model\wanlshop\OrderGoods')
			->where(['order_id' => $order_id])
			->select();
		$msgData = [];
		foreach ($orderGoods as $goods) {
			$msg = [
				'user_id' => $order['user_id'], // 推送目标用户
				'shop_id' => $this->shop->id, 
				'title' => '您的订单'.$state, // 推送标题
				'image' => $goods['image'], // 推送图片
				'content' => '您购买的商品 '.(mb_strlen($goods['title'],'utf8') >= 25 ? mb_substr($goods['title'],0,25,'utf-8').'...' : $goods['title']).' '.$state, 
				'type' => 'order',  // 推送类型
				'modules' => 'order',  // 模块类型
				'modules_id' => $order_id,  // 模块ID
				'come' => '订单'.$order['order_no'] // 来自
			];
			$msgData[] = $msg;
			$this->wanlchat->send($order['user_id'], $msg);
		}
		$notice = model('app\index\model\wanlshop\Notice')->saveAll($msgData);
	}


	// 客户取货
    public function selfPick(){
        if($this->request->isPost()){
            $order_id = $this->request->post('order_id');
            $order_id ? $order_id : ($this->error(__('非法请求')));
            // 判断权限
            try{
                $order = model('app\api\model\wanlshop\Order')->confirm($order_id,$this->shop->id);
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('ok', $order ? true : false);
        }
    }
}
